const app = getApp()
let qCloud = require("../../index.js");

Page({
  /** 页面的初始数据 */
  data: {
    imgPath: qCloud.config.STATIC_IMAGE_PATH,
    goodsId: null, // 货物ID
    goodsName: "", // 货物名称(货号)
    goodsCode: "", // 货物编号(编号)
    cooperateEnterpriseId: 0, // 合作企业
    cooperateEnterpriseName: "", // 合作企业名称
    warehouseId: 0, // 仓库ID
    warehouseName: "", // 仓库名称
    warehouseList: [], // 仓库列表
    goodsShelves: "", // 货架号
    warehouseInManner: "", // 入库方式
    warehouseInMannerTitle: "", // 入库方式名称
    warehouseInMannerList: [], // 入库方式列表
    inboundTotal: 0, // 入库总数
    showSpecsTypeModal: false, // 尺码类型标记
    specsTypeTemplateList: [], // 尺码类型模板列表-
    specsTypeTemplate: {}, // 尺码类型模板-
    specsTypeList: [], // 尺码类型列表-
    specsType: "", // 尺码类型
    specsTypeTitle: "", // 尺码类型
    imageId: "", // 图片
    imageUrl: "", // 图片
    showImg: false, // 是否显示图片上传组件
    remark: "", // 备注


    showModalStatus: false,
    cooperateEnterpriseList: [],
  },

  // 货物名称(货号)
  goodsNameInput(e) {
    let self = this;
    self.setData({
      goodsName: e.detail.value.trim()
    });
  },

  // 货物编号(编号)
  goodsCodeInput(e) {
    let self = this;
    self.setData({
      goodsCode: e.detail.value.trim()
    });
  },

  // 所属仓库
  warehouseChange(e) {
    let self = this;
    let index = e.detail.value;
    let warehouseList = self.data.warehouseList;
    self.setData({
      warehouseId: warehouseList[index].id, // 仓库ID
      warehouseName: warehouseList[index].title, // 仓库名称
    });
  },

  // 货架号
  goodsShelvesInput(e) {
    let self = this;
    self.setData({
      goodsShelves: e.detail.value.trim()
    });
  },

  // 入库方式
  warehouseInMannerChange(e) {
    let self = this;
    let index = e.detail.value;
    let warehouseInMannerList = self.data.warehouseInMannerList;
    self.setData({
      warehouseInManner: warehouseInMannerList[index].id, // 入库方式
      warehouseInMannerTitle: warehouseInMannerList[index].title, // 入库方式名称
    });
  },

  // 查找企业
  searchEnterprise() {
    let params = {}
    this.queryCooperateEnterpriseList(params);

    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    });

    this.animation = animation;
    animation.translateY(300).step();
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    });
    setTimeout(function () {
      animation.translateY(0).step();
      this.setData({
        animationData: animation.export()
      });
    }.bind(this), 200);
  },

  hideEnterpriseModal: function (e) {
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    });
    this.animation = animation;
    animation.translateY(300).step();
    this.setData({
      animationData: animation.export(),
    });
    setTimeout(function () {
      animation.translateY(0).step();
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200);

    this.setData({
      cooperateEnterpriseList: []
    })
  },

  searchInput: function (e) {
    let self = this;
    let params = {
      enterpriseName: e.detail.value
    };
    this.queryCooperateEnterpriseList(params);
  },

  // 确认选择企业
  confirmEnterprise(e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      cooperateEnterpriseId: this.data.cooperateEnterpriseList[index].cooperateEnterpriseId,
      cooperateEnterpriseName: this.data.cooperateEnterpriseList[index].cooperateEnterpriseName,
      showModalStatus: false
    })
  },

  // 合作企业
  cooperateEnterpriseNameChange(e) {
    let self = this;
    let index = e.detail.value;
    let cooperateEnterpriseList = self.data.cooperateEnterpriseList;
    self.setData({
      cooperateEnterpriseId: cooperateEnterpriseList[index].cooperateEnterpriseId,
      cooperateEnterpriseName: cooperateEnterpriseList[index].cooperateEnterpriseName,
    });
  },

  // 计算入库数量
  countInboundTotal() {
    let self = this;
    let inboundTotal = 0;

    let specsTypeList = self.data.specsTypeList;
    for (let i = 0; i < specsTypeList.length; i++) {
      let specsType = specsTypeList[i];
      for (let j = 0; j < specsType.specsList.length; j++) {
        let specsInfo = specsType.specsList[j];
        inboundTotal = inboundTotal * 1 + specsInfo.inboundQuantity * 1
      }
    }

    self.setData({
      inboundTotal: inboundTotal
    });
  },

  // 选择尺码类型模板
  specsTypeChange(e) {
    let self = this;
    let index = e.detail.value;
    let specsTypeTemplate = self.data.specsTypeTemplateList[index];

    let specsList = [];
    let templateSpecsList = specsTypeTemplate.specsList;
    for (let i = 0; i < templateSpecsList.length; i++) {
      let specsInfo = {
        specs: templateSpecsList[i],
        inboundQuantity: 0,
        unitPrice: 0,
        totalPrice: 0,
      };
      specsList.push(specsInfo);
    }
    let specsTypeList = [{
      colour: "",
      specsList: specsList
    }];

    self.setData({
      showSpecsTypeModal: true,
      specsTypeTemplate: specsTypeTemplate,
      specsTypeList: specsTypeList,
      specsType: specsTypeTemplate.code,
      specsTypeTitle: specsTypeTemplate.title
    });

    // 计算入库数量
    self.countInboundTotal();
  },

  // 颜色
  colourInput(e) {
    let self = this;
    let index = e.currentTarget.dataset.index;
    let specsTypeList = self.data.specsTypeList;
    specsTypeList[index]["colour"] = e.detail.value.trim();

    self.setData({
      specsTypeList: specsTypeList
    });
  },

  // 添加尺码类型
  addSpecsType(e) {
    let self = this;

    let specsList = [];
    let templateSpecsList = self.data.specsTypeTemplate.specsList;
    for (let i = 0; i < templateSpecsList.length; i++) {
      let specsInfo = {
        specs: templateSpecsList[i],
        inboundQuantity: 0,
        unitPrice: 0,
        totalPrice: 0,
      };
      specsList.push(specsInfo);
    }
    let specsType = {
      colour: "",
      specsList: specsList
    };
    let specsTypeList = self.data.specsTypeList;
    specsTypeList.push(specsType);

    self.setData({
      specsTypeList: specsTypeList
    });

    // 计算入库数量
    self.countInboundTotal();
  },

  // 删除尺码类型
  delSpecsType(e) {
    let self = this;
    let index = e.currentTarget.dataset.index;
    let specsTypeList = self.data.specsTypeList;
    specsTypeList.splice(index, 1);

    self.setData({
      specsTypeList: specsTypeList
    });

    // 计算入库数量
    self.countInboundTotal();
  },

  // 尺码
  specsInput(e) {
    let self = this;
    let index = e.currentTarget.dataset.index;
    let stIndex = e.currentTarget.dataset.stindex;
    let specsTypeList = self.data.specsTypeList;
    specsTypeList[index].specsList[stIndex]["specs"] = e.detail.value.trim();

    self.setData({
      specsTypeList: specsTypeList
    });
  },

  // 尺码数量
  inboundQuantityInput(e) {
    let self = this;
    let inboundQuantity = e.detail.value; // 数量
    let index = e.currentTarget.dataset.index;
    let stIndex = e.currentTarget.dataset.stindex;
    let specsTypeList = self.data.specsTypeList;
    specsTypeList[index].specsList[stIndex]["inboundQuantity"] = inboundQuantity.trim();

    let unitPrice = specsTypeList[index].specsList[stIndex]["unitPrice"]; // 单价
    specsTypeList[index].specsList[stIndex]["totalPrice"] = inboundQuantity * unitPrice; // 总价 = 数量 * 单价

    self.setData({
      specsTypeList: specsTypeList
    });

    // 计算入库数量
    self.countInboundTotal();
  },

  // 尺码单价
  unitPriceInput(e) {
    let self = this;
    let unitPrice = e.detail.value; // 单价
    let index = e.currentTarget.dataset.index;
    let stIndex = e.currentTarget.dataset.stindex;
    let specsTypeList = self.data.specsTypeList;
    specsTypeList[index].specsList[stIndex]["unitPrice"] = unitPrice.trim();

    let inboundQuantity = specsTypeList[index].specsList[stIndex]["inboundQuantity"]; // 数量
    specsTypeList[index].specsList[stIndex]["totalPrice"] = inboundQuantity * unitPrice; // 总价 = 数量 * 单价

    self.setData({
      specsTypeList: specsTypeList
    });
  },

  // 添加尺码
  addSpecs(e) {
    let self = this;
    let index = e.currentTarget.dataset.index;
    let specsTypeList = self.data.specsTypeList;
    let specsInfo = {
      specs: "",
      inboundQuantity: 0,
      unitPrice: 0,
      totalPrice: 0,
    };
    specsTypeList[index].specsList.push(specsInfo);

    self.setData({
      specsTypeList: specsTypeList
    });

    // 计算入库数量
    self.countInboundTotal();
  },

  // 删除尺码
  delSpecs(e) {
    let self = this;
    let index = e.currentTarget.dataset.index;
    let stIndex = e.currentTarget.dataset.stindex;
    let specsTypeList = self.data.specsTypeList;
    specsTypeList[index]["specsList"].splice(stIndex, 1);

    self.setData({
      specsTypeList: specsTypeList
    });

    // 计算入库数量
    self.countInboundTotal();
  },

  // 图片
  chooseImage() {
    let self = this;
    wx.chooseMedia({
      count: 1,
      mediaType: ["image"],
      sourceType: ["album", "camera"],
      maxDuration: 30,
      camera: "back",
      success(res) {
        wx.uploadFile({
          url: qCloud.api.uploadFile, //仅为示例，非真实的接口地址
          filePath: res.tempFiles[0].tempFilePath,
          name: "file",
          formData: {
            "file": res.tempFiles[0].tempFilePath,
            "fileType": "6"
          },
          header: qCloud.buildSessionHeader(),
          success(response) {
            let resJson = JSON.parse(response.data);
            if (resJson.code == 200) {
              self.setData({
                imageId: resJson.data.filesId,
                imageUrl: resJson.data.filesUrl,
                showImg: true
              });
            }
          },

          fail(error) {
            wx.showToast({
              title: error,
              icon: "error"
            })
          }
        })
      },
      fail(e) {}
    });
  },


  /** 生命周期函数--监听页面加载 */
  onLoad: function (options) {
    let self = this;
    self.setData({
      goodsId: options.goodsId
    });

    // 初始化尺码类型模板列表
    self.initSpecsTypeTemplateList();

    // 查询仓库列表
    self.queryWarehouseList();

    // 查询合作企业
    // self.queryCooperateEnterpriseList({});
  },

  // 查询合作企业列表
  queryCooperateEnterpriseList(params) {
    let self = this;
    app.fetchApis(self, qCloud.api.common_queryCooperateEnterpriseList, params, "POST", function (e) {
      let result = e.data;
      if (result.code == 200) {
        let data = result.data;
        self.setData({
          cooperateEnterpriseList: data.enterpriseList
        });
      }
    });
  },

  // 初始化尺码类型模板列表
  initSpecsTypeTemplateList() {
    let specsTypeTemplateList = [{
      title: "SML尺码",
      code: "SML",
      specsList: ["S", "M", "L", "XL", "2XL", "3XL", "4XL"]
    }, {
      title: "数字尺码",
      code: "NS",
      specsList: ["25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35"]
    }, {
      title: "自定义尺码",
      code: "CS",
      specsList: []
    }];
    let warehouseInMannerList = [{
      id: "1",
      title: "生产入库"
    }, {
      id: "2",
      title: "退货入库"
    }, {
      id: "3",
      title: "采购入库"
    }];
    let self = this;
    self.setData({
      specsTypeTemplateList: specsTypeTemplateList,
      warehouseInMannerList: warehouseInMannerList,
    });
  },

  /** 查询仓库列表 */
  queryWarehouseList: function () {
    let self = this;
    app.fetchApis(self, qCloud.api.common_queryWarehouseList, {}, "POST", function (e) {
      let result = e.data;

      if (result.code == 200) {
        let data = result.data;

        let warehouseList = [];
        for (let i = 0; i < data.warehouseList.length; i++) {
          let warehouseInfo = data.warehouseList[i];
          for (let i = 0; i < warehouseInfo.subWarehouseList.length; i++) {
            let subWarehouseInfo = warehouseInfo.subWarehouseList[i];
            let warehouse = {
              id: subWarehouseInfo.warehouseId,
              title: warehouseInfo.warehouseName + " : " + subWarehouseInfo.warehouseName,
            };
            warehouseList.push(warehouse);
          }
        }

        self.setData({
          warehouseList: warehouseList
        });
      }
    });
  },

  // 入库
  submitWarehouseIn() {
    let self = this;

    let title = self.checkParams();
    if (title != "") {
      wx.showToast({
        title: title,
        icon: "error"
      });
      return;
    }

    let specsList = []; // 规格列表
    let specsTypeList = self.data.specsTypeList;
    for (let i = 0; i < specsTypeList.length; i++) {
      let specsType = specsTypeList[i];
      for (let j = 0; j < specsType.specsList.length; j++) {
        let specsInfo = specsType.specsList[j];
        let specs = { // 规格
          goodsSpecsId: specsInfo.goodsSpecsId, // 货物规格ID:已存在货物规格增加入库数量时必送
          colour: specsType.colour, // 颜色
          specs: specsInfo.specs, // 尺码
          inboundQuantity: specsInfo.inboundQuantity, // 入库数量
          unitPrice: specsInfo.unitPrice, // 单价
          totalPrice: specsInfo.totalPrice, // 总价
        };
        specsList.push(specs);
      }
    }

    if (specsList.length > 0) {
      let params = {
        mark: "1", // 1-入库;2-货物入库;3-生产入库;
        warehouseId: self.data.warehouseId, // 仓库ID
        goodsId: self.data.goodsId, // 货物ID:已存在货物增加入库数量时必送
        goodsName: self.data.goodsName, // 货物名称
        goodsCode: self.data.goodsCode, // 货物编号
        goodsShelves: self.data.goodsShelves, // 货架号
        warehouseInManner: self.data.warehouseInManner, // 入库方式
        specsType: self.data.specsType, // 尺码类型
        inboundTotal: self.data.inboundTotal, // 入库总数
        cooperateEnterpriseId: self.data.cooperateEnterpriseId, // 合作企业
        cooperateEnterpriseName: self.data.cooperateEnterpriseName, // 合作企业名称
        imageId: self.data.imageId, // 图片
        remark: self.data.remark, // 备注
        specsList: specsList, // 规格列表
      }

      app.fetchApis(self, qCloud.api.warehouse_submitWarehouseIn, params, "POST", function (e) {
        let result = e.data;

        if (result.code == 200) {
          wx.navigateTo({
            url: "/pages/warehouse/index",
          });
        }
      });
    } else {
      wx.showToast({
        title: "请输入规格信息",
        icon: "error"
      });
    }
  },

  // 校验参数
  checkParams() {
    let self = this;
    if (!self.data.goodsName || self.data.goodsName == "") {
      return "请输入货号";
    }
    if (self.data.warehouseId == 0) {
      return "请选择仓库";
    }
    if (self.data.warehouseInManner == "") {
      return "请选择入库方式";
    }
    if (self.data.specsTypeList.length <= 0) {
      return "请选择规格信息";
    }
    return "";
  },

  /** 生命周期函数--监听页面初次渲染完成 */
  onReady: function () {},

  /** 生命周期函数--监听页面显示 */
  onShow: function () {},

  /** 生命周期函数--监听页面隐藏 */
  onHide: function () {},

  /** 生命周期函数--监听页面卸载 */
  onUnload: function () {},

  /** 页面相关事件处理函数--监听用户下拉动作 */
  onPullDownRefresh: function () {},

  /** 页面上拉触底事件的处理函数 */
  onReachBottom: function () {},

  /** 用户点击右上角分享 */
  onShareAppMessage: function () {}
});
